<?php
/**
 * @author huwhois<huwhois@163.com>
 */
namespace app\admin\controller;

use daswork\Controller;
use app\admin\model\SignBak;
use app\admin\model\Attenders;

class Index extends Base
{
    public function __construct()
    {
        parent::__construct();
        $this->model = new Attenders();
    }

    public function index()
    {
        $key = isset($_GET['key']) ? escapeString($_GET['key']) : '';
        $where = '';
        if ($key) {
            $where = "WHERE truename LIKE '$key%' OR phone LIKE '$key%' or organization LIKE '$key%'";
            $this->assign('key', $key);
        }
        
        $page = isset($_GET['page']) ? escapeString($_GET['page']) : 1;
        $data = $this->model->pageList($where, $page, 15);

        $this->assign('data', $data);
        $this->fetch();
    }

    public function info()
    {
        $id = $_GET['id'];
        if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])  && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
            if (!$id) {
                echo json_encode(['code' => 1, 'msg'=>'id不能为空']);
            }
            $data = $this->model->getOneById($id);

            echo json_encode(['code'=>0, 'data'=>$data]);
        } else {
            if (!$id) {
                echo "<script>alert('id 不能为空');history.back();</script>";
            }
            $data = $this->model->getOneById($id);
            $this->assign('data', $this->replaceDate($data));
            $this->fetch();
        }
    }
    
    // 替换报名表数据输出字符
    public function replaceDate($arr = []) {
        // 替换性别
        if (isset($arr['sex'])) {
            $arr['sex'] = ($arr['sex'] == 2) ? "女" : "男";
        }
        // 替换开票信息
        if (isset($arr['tax_type'])) {
            $arr['tax_type'] = ($arr['tax_type'] == 2) ? "专票" : "普票";
        }
        // 替换会议注册类型(注册费)
        if (isset($arr['fee_type'])) {
            $arr['fee_type'] = ($arr['fee_type'] == 2) ? "学生(1200/人)" : "普通(2000/人)";
        }
        //是否做报告
        if (isset($arr['is_report'])) {
            $arr['is_report'] = ($arr['is_report'] == 1) ? "是" : "否";
        }
        // 酒店
        if (isset($arr['room_type'])) {
            $arr['room_type'] = ($arr['room_type'] == 1) ? "标准间" : "商务房";
        }
        if (isset($arr['is_share'])) {
            $arr['is_share'] = ($arr['is_share'] == 1) ? "是" : "否";
        }
        // 支付形式
        if (isset($arr['pay_type'])) {
            $arr['pay_type'] = ($arr['pay_type'] == 1) ? "汇款" : "现场缴费";
        }
        // 报名时间
        if (isset($arr['create_time'])) {
            date_default_timezone_set("PRC");
            $arr['create_time'] = date("Y-m-d H:i:s", $arr['create_time']);
        }

        return $arr;
    }

    public function test()
    {
        $res = $this->model->getByTruenameAndPhone('测试', '13366667777');
        var_dump($res);
        exit;
    }

    public function save()
    {
        $params = escapeString($_POST);
        // echo json_encode($params);
        // exit;

        if (empty($params['truename']) || empty($params['phone'])) {
            die(json_encode(['code'=>1, 'msg'=>'姓名 or 电话不能为空']));
        }

        $res = $this->model->getByTruenameAndPhone($params['truename'], $params['phone']);
        if ($res) {
            die(json_encode(['code'=>1, 'msg'=>'已经报名成功，请勿重复提交']));
        }
        // var_dump($res);
        // exit;
        $data = [
            "meeting_id" => 3,
            'truename' => $params['truename'],
            'organization' => $params['organization'],
            'position' => $params['position'],
            'sex' => $params['sex'],
            'phone' => $params['phone'],
            'email' => $params['email'],
            'fee_type' => intval($params['feeType']),
            'is_report' => intval($params['isReport']),
            'report_title' => $params['reportTitle'],
            'hotel_type' => 1,
            'room_type' => intval($params['roomType']),
            'is_share' => intval($params['isShare']),
            'pay_type' => intval($params['payType']),
            'is_pay' => intval($params['isPay']),
            'money' =>floatval($params['money']),
            'tax_type' => intval($params['taxType']),
            'tax_title' => $params['taxTitle'],
            'tax_number' => $params['taxNumber'],
            'bank_account' => $params['bankAccount'],
            'company_address' => $params['companyAddress'],
            'company_phone' => $params['companyPhone'],
            'mailing_address' => $params['mailingAddress'],
            'postcode' => $params['postcode'],
            'remark' => $params['remark'],
            'member_type'=> 10,
            'status' => 0,
            'token' => md5($params['truename'] . $params['phone']),
            'create_time' => time()
        ];

        $id = $params['id'];
        if ($id) {
            $data['id'] = $id;
            $res = $this->model->updateById($data);
        } else {
            $res = $this->model->save($data);
        }

        if (!$res) {
            echo json_encode(['code' => 2, 'msg'=>$this->model->lastErrorMsg()]);
        } else {
            echo json_encode(['code' => 0]);
        }
    }

    public function delete()
    {
        $id = escapeString($_POST['id']);
        if (!$id) {
            echo json_encode(['code' => 1, 'msg'=>'id不能为空']);
        }
        $res = $this->model->deleteById($id);
        if (!$res) {
            echo json_encode(['code' => 2, 'msg'=>$this->model->lastErrorMsg()]);
        } else {
            echo json_encode(['code' => 0]);
        }
    }

    public function export()
    {
        require_once (VENDOR . DS .'phpoffice/PHPExcel.php');
        // Create new PHPExcel object
        $objPHPExcel = new \PHPExcel();

        // Set document properties
        $objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
            ->setLastModifiedBy("Maarten Balliauw")
            ->setTitle("Office 2007 XLSX Test Document")
            ->setSubject("Office 2007 XLSX Test Document")
            ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
            ->setKeywords("office 2007 openxml php")
            ->setCategory("Test result file");

        // 设置D,E,F,G,I列宽
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(12);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(13);
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20); 
        $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(13); 
        $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(18);

        // 设置E,G,J,L,M,O,R列为文本格式
        $objPHPExcel->getActiveSheet()->getStyle('E')->getNumberFormat()
            ->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);
        $objPHPExcel->getActiveSheet()->getStyle('G')->getNumberFormat()
            ->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);
        $objPHPExcel->getActiveSheet()->getStyle('J')->getNumberFormat()
            ->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);
        $objPHPExcel->getActiveSheet()->getStyle('L')->getNumberFormat()
            ->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);
        $objPHPExcel->getActiveSheet()->getStyle('M')->getNumberFormat()
            ->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);
        $objPHPExcel->getActiveSheet()->getStyle('O')->getNumberFormat()
            ->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);
        $objPHPExcel->getActiveSheet()->getStyle('R')->getNumberFormat()
            ->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);

        // 添加表头
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', 'ID')
            ->setCellValue('B1', '姓名')
            ->setCellValue('C1', '所属机构')
            ->setCellValue('D1', '职位')
            ->setCellValue('E1', '性别')
            ->setCellValue('F1', '电话')
            ->setCellValue('G1', '邮箱')
            ->setCellValue('H1', '注册费(类型)')
            ->setCellValue('I1', '是否做报告')
            ->setCellValue('J1', '报告题目')
            ->setCellValue('K1', '酒店')
            ->setCellValue('L1', '房型')
            ->setCellValue('M1', '是否接受合住')
            ->setCellValue('N1', '付款方式')
            ->setCellValue('O1', '是否付款')
            ->setCellValue('P1', '金额')
            ->setCellValue('Q1', '开票类型')
            ->setCellValue('R1', '发票抬头')
            ->setCellValue('S1', '纳税人识别号')
            ->setCellValue('T1', '开户行及账号')
            ->setCellValue('U1', '单位电话')
            ->setCellValue('V1', '单位地址')
            ->setCellValue('W1', '邮寄地址')
            ->setCellValue('X1', '邮编')
            ->setCellValue('Y1', '备注')
            ->setCellValue('Z1', '报名时间');
        
        $data = $this->model->dataList();

        if ($data) {
            $count = 1;
            foreach ($data as $value) {
                $count += 1;
                //替换性别等字符
                $value = $this->replaceDate($value);
                // 字符型数字前加空格" ", 以字符型插入excel
                $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('A'.$count, $value['id'])
                    ->setCellValue('B'.$count, $value['truename'])
                    ->setCellValue('C'.$count, $value['organization'])
                    ->setCellValue('D'.$count, $value['position'])
                    ->setCellValue('E'.$count, $value['sex'])
                    ->setCellValue('F'.$count, $value['phone'])
                    ->setCellValue('G'.$count, $value['email'])
                    ->setCellValue('H'.$count, $value['fee_type'])
                    ->setCellValue('I'.$count, $value['is_report'])
                    ->setCellValue('J'.$count, $value['report_title'])
                    ->setCellValue('K'.$count, $value['hotel_type'])
                    ->setCellValue('L'.$count, $value['room_type'])
                    ->setCellValue('M'.$count, $value['is_share'])
                    ->setCellValue('N'.$count, $value['pay_type'])
                    ->setCellValue('O'.$count, $value['is_pay'])
                    ->setCellValue('P'.$count, $value['money'])
                    ->setCellValue('Q'.$count, $value['tax_type'])
                    ->setCellValue('R'.$count, $value['tax_title'])
                    ->setCellValue('S'.$count, $value['tax_number'])
                    ->setCellValue('T'.$count, $value['bank_account'])
                    ->setCellValue('U'.$count, $value['company_address'])
                    ->setCellValue('V'.$count, $value['company_phone'])
                    ->setCellValue('W'.$count, $value['mailing_address'])
                    ->setCellValue('X'.$count, $value['postcode'])
                    ->setCellValue('Y'.$count, $value['remark'])
                    ->setCellValue('Z'.$count, $value['create_time']);
            }
        }

        // 命名标签页
        $objPHPExcel->getActiveSheet()->setTitle('2020耐蚀钢会网络报名表');

        // Set active sheet index to the first sheet, so Excel opens this as the first sheet
        $objPHPExcel->setActiveSheetIndex(0);

        // Redirect output to a client’s web browser (Excel2007)
        $filename = date('YmdHis') . ".xlsx";
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename=' . $filename);
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');

        // If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;
    }

    public function doPrint()
    {
        $id = $_POST['id'];
        if (!$id) {
            echo json_encode(['code' => 1, 'msg'=>'id不能为空']);
        }
        $time = time();
        $sql = "UPDATE `sign_bak` SET badge=1, status=1, printNum=printNum+1, printTime=$time WHERE member_id=$id";

        $res = $this->model->query($sql);
        if ($res===false) {
            echo json_encode(['code' => 2, 'msg'=>$this->model->lastErrorMsg()]);
        }

        $data = $this->model->getOneById($id);
        $data['img'] = $this->getQrcode($data['token']);
        header("Content-type: text/html; charset=utf-8");
        // var_dump($data);
        echo json_encode(['code'=>0, 'data'=>$data]);
    }

    public function getQrcode($token)
    {
        include_once(VENDOR . 'phpqrcode' . DS . 'phpqrcode.php');
        $codeUrl = 'http://meeting.ecorr.org/qrcode/webmeeting.html?token=' . $token;
        ob_start();//开启缓冲区
        \QRcode::png($codeUrl, false, 'L', 6, 1);//生成二维码
        $img = ob_get_contents();//获取缓冲区内容
        ob_end_clean();//清除缓冲区内容
        $imgInfo = 'data:image/png;base64,' . chunk_split(base64_encode($img));//转base64
        ob_flush();
        return $imgInfo;
    }

    public function printReceipt()
    {
        $ids = escapeString($_GET['ids']);
        $idarr = explode(',', $ids);
        $id = '(';
        foreach ($idarr as $value) {
            $id .= intval($value) . ',';
        }
        $id = rtrim($id, ',');
        $id .=")";
        $res = $this->model->dataList("where id IN $id");
        // var_dump($res);
        // exit;
        $name = [];
        $money = 0;
        $organization = '';
        foreach ($res as $val) {
            $name[] = $val['truename'];
            if ($val['fee_type']==1) {
                $money += 2000;
            } else {
                $money += 1200;
            }
            $organization = $val['organization'];
        }
        $pname = implode(',', $name);

        $this->assign('time', date('Y-m-d'));
        $this->assign('pname', $pname);
        $this->assign('money', $money);
        $this->assign('organization', $organization);
        $this->assign('dxmoney', $this->convertAmountToCn($money));
        $this->fetch();
    }
    
    /**
    * 将数值金额转换为中文大写金额
    * @param $amount float 金额(支持到分)
    * @param $type   int   补整类型,0:到角补整;1:到元补整
    * @return mixed 中文大写金额
    */
    public function convertAmountToCn($amount, $type = 1) {
        // 判断输出的金额是否为数字或数字字符串
        if(!is_numeric($amount)){
            return "要转换的金额只能为数字!";
        }
        
        // 金额为0,则直接输出"零元整"
        if($amount == 0) {
            return "人民币零元整";
        }
        
        // 金额不能为负数
        if($amount < 0) {
            return "要转换的金额不能为负数!";
        }
        
        // 金额不能超过万亿,即12位
        if(strlen($amount) > 12) {
            return "要转换的金额不能为万亿及更高金额!";
        }
        
        // 预定义中文转换的数组
        $digital = array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');
        // 预定义单位转换的数组
        $position = array('仟', '佰', '拾', '亿', '仟', '佰', '拾', '万', '仟', '佰', '拾', '元');
        
        // 将金额的数值字符串拆分成数组
        $amountArr = explode('.', $amount);
        
        // 将整数位的数值字符串拆分成数组
        $integerArr = str_split($amountArr[0], 1);
        
        // 将整数部分替换成大写汉字
        //    $result = '人民币';
        $result = '';
        $integerArrLength = count($integerArr);     // 整数位数组的长度
        $positionLength = count($position);         // 单位数组的长度
        $zeroCount = 0;                             // 连续为0数量
        for($i = 0; $i < $integerArrLength; $i++) {
            // 如果数值不为0,则正常转换
            if($integerArr[$i] != 0){
                // 如果前面数字为0需要增加一个零
                if($zeroCount >= 1){
                    $result .= $digital[0];
                }
                $result .= $digital[$integerArr[$i]] . $position[$positionLength - $integerArrLength + $i];
                $zeroCount = 0;
            }else{
                $zeroCount += 1;
                // 如果数值为0, 且单位是亿,万,元这三个的时候,则直接显示单位
                if(($positionLength - $integerArrLength + $i + 1)%4 == 0){
                    $result = $result . $position[$positionLength - $integerArrLength + $i];
                }
            }
        }
        
        // 如果小数位也要转换
        if($type == 0) {
            // 将小数位的数值字符串拆分成数组
            $decimalArr = str_split($amountArr[1], 1);
            // 将角替换成大写汉字. 如果为0,则不替换
            if($decimalArr[0] != 0){
                $result = $result . $digital[$decimalArr[0]] . '角';
            }
            // 将分替换成大写汉字. 如果为0,则不替换
            if($decimalArr[1] != 0){
                $result = $result . $digital[$decimalArr[1]] . '分';
            }
        }else{
            $result = $result . '整';
        }
        return $result;
    }

    public function receipt()
    {
        $params = $_GET;
        // var_dump($params);
        $this->assign('data', $params);
        $this->fetch();
    }

    public function getab($y = 1000)
    {
        $res = [];
        $sum = 0;
        $s = 0;
        // echo mt_rand(1, 10);
        // var_dump($y);
        while(1){
            $ab = [];
            $ab['a'] = mt_rand(10, 20);
            $ab['b'] = mt_rand(10, 20);
            $sum += $ab['a'] * $ab['b'];
            if ($sum > $y) {
                break;
            }
            $s = $sum;
            $res[] = $ab;
        }
        $sy = $y - $s;
        var_dump($s);
        var_dump($sy);
        while(1){
            $ab = [];
            $ab['a'] = mt_rand(1, 200);
            $ab['b'] = mt_rand(1, 200);

            if ($ab['a'] * $ab['b'] == $sy) {
                $res[] = $ab;
                break;
            }
        }

        return $res;
    }

}
